import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useLocation } from 'react-router-dom';
import { useUserProfile } from '../hooks/useUserProfile';
import { useChatHistoryManager } from '../hooks/useChatHistoryManager';
import LoginModal from './LoginModal';
import LogoutConfirmModal from './LogoutConfirmModal';
import { getDynamicFonts } from '@/utils/fontUtils';
import ptVip from '@/assets/images/sidbar/1.webp';
import xyVip from '@/assets/images/sidbar/2.webp';
import zzVip from '@/assets/images/sidbar/3.webp';


// 菜单项配置，与Sidebar保持一致
const bottomMenuItems = [
    {
        key: 'Explore',
        icon: 'fas fa-compass',
        labelKey: 'Explore',
        path: '/',
    },
    {
        key: 'chatCollection',
        icon: 'fas fa-comments',
        labelKey: 'chatCollection',
        path: '/chat-collection',
    },
    {
        key: 'generateImage',
        icon: 'fas fa-image',
        labelKey: 'generateImage',
        path: '/collections',
    },
    // {
    //     key: 'createCharacter',
    //     icon: 'fas fa-user-plus',
    //     labelKey: 'createCharacter',
    //     path: '/create-character',
    // },
    {
        key: 'becomePremium',
        icon: 'fas fa-crown',
        labelKey: 'becomePremium',
        path: '/subscriptions',
    },
];

interface BottomNavigationProps {
    isMobile: boolean;
    activeTab: string;
    setActiveTab: (tab: string) => void;
}
// , setActiveTab
const BottomNavigation: React.FC<BottomNavigationProps> = ({ isMobile, activeTab }) => {
    const { t, i18n } = useTranslation();
    const navigate = useNavigate();
    const location = useLocation();
    const dynamicFonts = getDynamicFonts(i18n);

    // 使用useUserProfile代替useAuth，确保与Sidebar一致的登录状态管理
    const {
        isLoggedIn,
        userData,
        showLoginModal,
        isRegisterMode,
        closeLoginModal,
        openLoginModal,
        handleLoginSuccessAndUpdateTab,
        showLogoutConfirm,
        confirmLogout,
        cancelLogout
    } = useUserProfile();

    const { loadLatestChatFromHistory } = useChatHistoryManager();
    const [_, setForceUpdate] = useState(0); // 用于强制刷新

    // 检查登录状态并显示登录弹窗（如果未登录）
    const checkLoginAndShowModal = () => {
        if (!isLoggedIn) {
            openLoginModal(false);
            return false;
        }
        return true;
    };

    // 包装登录成功处理函数
    const handleLoginSuccess = () => {
        handleLoginSuccessAndUpdateTab(() => { });
    };

    // 判断当前菜单项是否激活
    const isActive = (item: typeof bottomMenuItems[0]) => {
        const currentPath = location.pathname;
        if (item.key === 'Explore') {
            return currentPath === '/';
        }
        return currentPath === item.path;
    };

    // 只在移动端显示
    if (!isMobile) return null;

    // 完全复刻Sidebar的点击逻辑
    const handleMenuClick = (e: React.MouseEvent, item: typeof bottomMenuItems[0]) => {
        e.preventDefault();
        if (item.key === 'Explore') {
            navigate('/');
            setForceUpdate(v => v + 1);
            return;
        }
        if (item.key === 'becomePremium') {
            if (checkLoginAndShowModal()) {
                navigate('/subscriptions');
                setForceUpdate(v => v + 1);
            }
            return;
        }
        if (item.key === 'createCharacter') {
            // 检查登录状态
            if (!checkLoginAndShowModal()) {
                return;
            }
            // 已登录，使用新的API方式获取最新聊天记录
            (async () => {
                try {
                    const result = await loadLatestChatFromHistory();
                    if (result.chatId) {
                        // console.log(`🎯 跳转到最新聊天: ${result.chatId}`);
                        // 保存当前对话ID到sessionStorage
                        sessionStorage.setItem('currentConversationId', result.chatId);
                        navigate('/conversation');
                    } else {
                        // console.log('💡 没有聊天历史，跳转到首页');
                        navigate('/');
                    }
                    setForceUpdate(v => v + 1);
                } catch (error) {
                    // console.error('❌ 获取最新聊天记录失败:', error);
                    console.error('loadLatestChatFromHistory failed', error);
                    // 发生错误时跳转到首页
                    navigate('/');
                    setForceUpdate(v => v + 1);
                }
            })();
            return;
        }
        if (item.key === 'chatCollection') {
            // 检查登录
            if (!checkLoginAndShowModal()) return;
            // 使用新的API方式获取最新聊天记录
            (async () => {
                try {
                    const result = await loadLatestChatFromHistory();
                    if (Array.isArray(result) && result.length > 0) {
                        const firstChat = result[0];
                        // 保存当前对话ID到sessionStorage
                        sessionStorage.setItem('currentConversationId', firstChat.id);
                        navigate('/conversation');

                    } else {
                        // console.log('没有聊天历史，不进行跳转');
                    }
                } catch (error) {
                    // console.error('❌ 获取聊天历史失败:', error);
                    console.error('loadLatestChatFromHistory failed', error);
                }
            })();
            return;


        }
        // 其他菜单项（如generateImage）需要登录检查
        if (checkLoginAndShowModal()) {
            navigate(item.path);
            setForceUpdate(v => v + 1);
        }
    };

    return (
        <>
            <div
                className="fixed bottom-0 left-0 right-0 bg-[rgb(19,19,19)] border-t border-[rgb(54,54,54)] z-50"
                style={{
                    width: '100vw',
                    paddingBottom: 'env(safe-area-inset-bottom, 0px)',
                    fontFamily: dynamicFonts.font3
                }}
            >
                <div className="flex justify-around items-center py-2">
                    {bottomMenuItems.map((item) => {
                        const active = isActive(item);
                        const activeColor = 'rgb(231, 82, 117)';
                        const defaultColor = 'rgb(209, 209, 209)';
                        return (
                            <button
                                key={item.key}
                                className="flex flex-col items-center justify-center py-2 px-1 transition-colors duration-200 min-w-0 flex-1"
                                onClick={(e) => handleMenuClick(e, item)}
                                style={{
                                    color: active ? activeColor : defaultColor,
                                    background: 'transparent',
                                    border: 'none',
                                    outline: 'none'
                                }}
                            >
                                {item.key === 'becomePremium' && userData && userData.vip_live ? (
                                    <>
                                        {userData.vip_live === 1 && <img src={ptVip} alt="PT VIP" className="w-7 h-7 mb-[0.4rem] -mt-[0.1rem]" style={{ objectFit: 'contain' }} />}
                                        {userData.vip_live === 2 && <img src={xyVip} alt="XY VIP" className="w-7 h-7 mb-[0.4rem] -mt-[0.1rem]" style={{ objectFit: 'contain' }} />}
                                        {userData.vip_live === 3 && <img src={zzVip} alt="ZZ VIP" className="w-7 h-7 mb-[0.4rem] -mt-[0.1rem]" style={{ objectFit: 'contain' }} />}
                                    </>
                                ) : (
                                    <i
                                        className={`${item.icon} text-lg mb-1`}
                                        style={{ color: active ? activeColor : defaultColor }}
                                    />
                                )}
                                <span
                                    className="text-xs font-medium truncate max-w-full"
                                    style={{
                                        color: active ? activeColor : defaultColor,
                                        fontSize: '0.7rem',
                                        lineHeight: '1'
                                    }}
                                >
                                    {item.key === 'becomePremium' && userData && userData.vip_live ? t('subscription.upgrade') : t(item.labelKey)}
                                </span>
                            </button>
                        );
                    })}
                </div>
            </div>

            {/* Login Modal - 这是关键！必须渲染LoginModal组件 */}
            <LoginModal
                show={showLoginModal}
                onClose={closeLoginModal}
                onLoginSuccess={handleLoginSuccess}
                activeTab={activeTab}
                initialRegister={isRegisterMode}
            />

            {/* 退出登录确认弹窗 */}
            <LogoutConfirmModal
                show={showLogoutConfirm}
                onClose={cancelLogout}
                onConfirm={confirmLogout}
            />
        </>
    );
};

export default BottomNavigation; 